package com.company.manage.system.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashSet;

/**
 * Created by HuangYong on 2016/1/23.
 * desc: session监听器
 */
@WebListener
public class SessionListener implements HttpSessionListener {
    private static final String TAG = "SessionListener";

    private static final Logger LOGGER = LoggerFactory.getLogger(SessionListener.class);


    @Override
    public void sessionCreated(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        ServletContext application = session.getServletContext();

        /*在application范围由一个HashSet集保存所有的session*/
        HashSet sessions = (HashSet) application.getAttribute("sessions");

        if (sessions == null) {
            sessions = new HashSet();
            application.setAttribute("sessions", sessions);
        }

        /* 新创建的session均添加到HashSet集合中*/
        /*使用sessions.size()获取当前活动的session数，即为“在线人数”*/
        sessions.add(session);
        LOGGER.info("session：" + session.getId() + " add");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {

        HttpSession session = event.getSession();
        ServletContext application = session.getServletContext();
        HashSet sessions = (HashSet) application.getAttribute("sessions");

        /*        销毁的session均从HashSet集中移除*/
        sessions.remove(session);
        LOGGER.info("session：" + session.getId() + " remove");

    }
}